import Vue from 'vue'
import VueRouter from 'vue-router'
// 路由懒加载
const Login = () => import('@/views/login/Index')
const Layout = () => import('@/views/layout/Index')
const Home = () => import('@/views/home/Index')
const Article = () => import('@/views/article/Index')
const Pubulish = () => import('@/views/publish/Index')
const Image = () => import('@/views/image/Index')
const Comment = () => import('@/views/comment/Index')
const Fans = () => import('@/views/fans/Index')
const Setting = () => import('@/views/setting/Index')

Vue.use(VueRouter)

// 路由配置表
const routes = [
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    // 命名路由 layout 有一个默认子路由，这个名字没有意义，所以警告
    // 正确的做法是：如果有默认子路由，就不要给父路由起名字了
    path: '/',
    // name: 'layout',
    component: Layout,
    children: [
      { path: '', name: 'home', component: Home },
      { path: '/article', name: 'article', component: Article },
      { path: '/publish', name: 'publish', component: Pubulish },
      { path: '/image', name: 'image', component: Image },
      { path: '/comment', name: 'comment', component: Comment },
      { path: '/fans', name: 'fans', component: Fans },
      { path: '/setting', name: 'persetting', component: Setting }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 路由导航守卫：说白了所有页面的导航都会经过这里
// 守卫页面的导航的
// to：要去的路由信息
// from：来自哪里的路由信息
// next：放行方法
router.beforeEach((to, from, next) => {
  // 如果要访问的页面不是 /login，校验登录状态
  // 如果没有登录，则跳转到登录页面
  // 如果登录了，则允许通过
  // 允许通过
  // next()
  const user = JSON.parse(window.localStorage.getItem('User'))

  // 校验非登录页面的登录状态
  if (to.path !== '/login') {
    if (user) {
      // 已登录，允许通过
      next()
    } else {
      // 没有登录，跳转到登录页面
      next('/login')
    }
  } else {
    // 登录页面，正常允许通过
    next()
  }
})

export default router
